/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import common.Constant;
import dao.OrderDAO;
import dao.OrderDetailDAO;
import dao.ProductDAO;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.OrderDetailsModel;
import model.OrderModel;
import model.ProductModel;

/**
 *
 * @author ThanhToan
 */
public class ShoppingCardController extends HttpServlet {
    private String URL = "";

    private Integer mapParameterToModel(HttpServletRequest req
			,HttpServletResponse res
				,OrderModel orderModel) {
        int countRowSelect = 0;
        int count = Integer.parseInt(req.getParameter("txtNo").trim().toString());
        if (req.getParameter("totalAmount").toString().trim() != null) {
			orderModel.setTotalAmount(req.getParameter("totalAmount").toString().trim()); }
        if (req.getParameter("discount").toString().trim() != null) {
			orderModel.setDiscount(req.getParameter("discount").toString().trim()); }
        orderModel.setAccID(req.getSession().getAttribute("userID").toString());
        ArrayList<OrderDetailsModel> orderDetailList = new ArrayList<OrderDetailsModel>();
        for(Integer i = 1; i<=count; i++){
            OrderDetailsModel orderDetailModel = new OrderDetailsModel();
            if (req.getParameter("txtProductID"+i.toString()) != null) {
			orderDetailModel.setProductID(req.getParameter("txtProductID" + i.toString().trim())); }
            if (req.getParameter("txtProductName"+i.toString()) != null) {
			orderDetailModel.setProductName(req.getParameter("txtProductName" + i.toString().trim())); }
            if (req.getParameter("txtPrice"+i.toString()) != null) {
			orderDetailModel.setPrice(req.getParameter("txtPrice"+i.toString().trim())); }
            if (req.getParameter("txtNum"+i.toString()) != null) {
			orderDetailModel.setNumber(req.getParameter("txtNum"+i.toString().trim())); }
            if (req.getParameter("txtAmount"+i.toString()) != null) {
			orderDetailModel.setValue(req.getParameter("txtAmount"+i.toString().trim())); }
            if (req.getParameter("chkRow" + i.toString()) != null
					&& req.getParameter("action").equals("remove")) {
			// Row nay dang bi chon de DELETE ==> ko dua vao Object Model
		String id = orderDetailModel.getId();
                OrderDetailDAO.deleteOrderDetailsByID(id);
                countRowSelect++; 
		req.setAttribute("msgDeleteRow", "remove");
            }
            else{
                orderDetailList.add(orderDetailModel);
            }
        }
        orderModel.setOrderDetailList(orderDetailList);
        return countRowSelect;
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        doPost(request, response);
    } 

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        actionCard(request, response);
    }

    @SuppressWarnings("element-type-mismatch")
    protected void actionCard(HttpServletRequest request, HttpServletResponse response)
                                                        throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        ArrayList<OrderDetailsModel> shopCardModel = new ArrayList<OrderDetailsModel>();
        try {
            HttpSession session = request.getSession(true);
            ProductModel productModel = new ProductModel();
            if(session.getAttribute("shoppingCard")!=null){
                shopCardModel = (ArrayList<OrderDetailsModel>) (session.getAttribute("shoppingCard"));
            }
            String action = request.getParameter("action");
            String productID = request.getParameter("productID");

            if(action.equals("add")){ // add item to shop card
                productModel = ProductDAO.getProductByProID(productID); // get product information
                OrderDetailsModel item = new OrderDetailsModel(); // add product info in to orderModel
                item = OrderDAO.addProductToShopCard(productModel);
                boolean check = true;
                if(shopCardModel.size()<1){
                    Constant.NUM_ROWS = 0;
                }
                for(int i = 0; i < shopCardModel.size(); i++){
                    if(item.getProductID().equals(shopCardModel.get(i).getProductID())){
                        int num = Integer.parseInt(shopCardModel.get(i).getNumber()) + 1;
                        shopCardModel.get(i).setNumber(String.valueOf(num));
                        check = false;
                    }
                }
                if(check == true){ //add new product
                    shopCardModel.add(item);
                }
                Constant.NUM_ROWS++;
                URL = "showproduct.jsp?cateID=" + productModel.getCateID() + "&addtocard="+ productModel.getProName();
                session.setAttribute(Constant.SHOPPING_CARD, shopCardModel);
            }

            if(!action.equals("add")){
                OrderModel orderModel = new OrderModel();
                Integer countRowSelected = mapParameterToModel(request, response, orderModel);
                if(action.equals("remove")){
                    Constant.NUM_ROWS -= countRowSelected;
                    URL = "showcart.jsp?remove=yes";
                    session.setAttribute(Constant.SHOPPING_CARD, orderModel.getOrderDetailList());
                }
                if(action.equals("checkout")){
                    if(OrderDAO.insertOrder(orderModel)){
                        URL = "checkout.jsp";
                        session.setAttribute(Constant.SHOPPING_CARD, "");
                    }
                    shopCardModel.clear();
                }
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
        RequestDispatcher rd = request.getRequestDispatcher(URL);
        rd.forward(request, response);
    } 

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
